#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
完整权限系统诊断脚本
诊断数据库权限系统的所有问题
"""

import sys
sys.path.append('e:/DEV_VISION')
from app import create_app

def comprehensive_permission_diagnosis():
    """完整诊断权限系统"""
    app = create_app()
    with app.app_context():
        from backend.models.user import User
        from backend.models.role import Role
        from backend.models.permission import Permission
        from backend.models.user_role import UserRole
        from backend.models.role_permission import RolePermission
        
        print("="*80)
        print("🔍 完整权限系统诊断报告")
        print("="*80)
        
        # 1. 检查基础数据
        print("\n📊 1. 基础数据统计")
        print("-" * 40)
        
        total_users = User.query.count()
        total_roles = Role.query.count()
        total_permissions = Permission.query.count()
        total_user_roles = UserRole.query.count()
        total_role_permissions = RolePermission.query.count()
        
        print(f"用户总数: {total_users}")
        print(f"角色总数: {total_roles}")
        print(f"权限总数: {total_permissions}")
        print(f"用户角色关联数: {total_user_roles}")
        print(f"角色权限关联数: {total_role_permissions}")
        
        # 2. 检查系统管理员
        print("\n👤 2. 系统管理员检查")
        print("-" * 40)
        
        admin_user = User.query.filter_by(username='系统管理员').first()
        if admin_user:
            print(f"✅ 系统管理员存在，ID: {admin_user.id}")
            
            # 检查角色关联
            user_roles = UserRole.query.filter_by(user_id=admin_user.id).all()
            print(f"角色关联数量: {len(user_roles)}")
            
            admin_role_ids = []
            for ur in user_roles:
                role = Role.query.get(ur.role_id)
                if role:
                    admin_role_ids.append(role.id)
                    print(f"  - 角色: {role.name} (ID: {role.id})")
            
            # 统计所有权限
            all_admin_permissions = set()
            for role_id in admin_role_ids:
                role_perms = RolePermission.query.filter_by(role_id=role_id).all()
                for rp in role_perms:
                    all_admin_permissions.add(rp.permission_id)
            
            print(f"系统管理员总权限数: {len(all_admin_permissions)}")
            
            # 检查是否有system:manage权限
            system_manage_perm = Permission.query.filter_by(code='system:manage').first()
            if system_manage_perm:
                has_system_manage = system_manage_perm.id in all_admin_permissions
                print(f"system:manage权限: {'✅ 有' if has_system_manage else '❌ 缺失'}")
            else:
                print("❌ system:manage权限不存在于数据库中")
        else:
            print("❌ 系统管理员用户不存在")
        
        # 3. 检查admin角色
        print("\n🏷️ 3. admin角色检查")
        print("-" * 40)
        
        admin_role = Role.query.filter_by(name='admin').first()
        if admin_role:
            print(f"✅ admin角色存在，ID: {admin_role.id}")
            
            role_perms = RolePermission.query.filter_by(role_id=admin_role.id).all()
            print(f"admin角色权限数: {len(role_perms)}")
            
            # 获取权限详情
            perm_codes = []
            for rp in role_perms:
                perm = Permission.query.get(rp.permission_id)
                if perm:
                    perm_codes.append(perm.code)
            
            print("admin角色权限列表（前10个）:")
            for i, code in enumerate(sorted(perm_codes)[:10]):
                print(f"  {i+1}. {code}")
            if len(perm_codes) > 10:
                print(f"  ... 还有 {len(perm_codes)-10} 个权限")
        else:
            print("❌ admin角色不存在")
        
        # 4. 检查权限完整性
        print("\n🔐 4. 权限完整性检查")
        print("-" * 40)
        
        # 检查关键权限是否存在
        critical_permissions = [
            'system:manage', 'user:read', 'student:read', 'role:read', 
            'permission:read', 'vision:read', 'intervention:read'
        ]
        
        missing_permissions = []
        for perm_code in critical_permissions:
            perm = Permission.query.filter_by(code=perm_code).first()
            if perm:
                print(f"✅ {perm_code} (ID: {perm.id})")
            else:
                print(f"❌ {perm_code} - 缺失")
                missing_permissions.append(perm_code)
        
        # 5. 检查数据库表结构
        print("\n🗄️ 5. 数据库表结构检查")
        print("-" * 40)
        
        # 检查表是否存在关键字段
        try:
            # 测试查询各个表
            User.query.first()
            print("✅ users表结构正常")
            
            Role.query.first()
            print("✅ roles表结构正常")
            
            Permission.query.first()
            print("✅ permissions表结构正常")
            
            UserRole.query.first()
            print("✅ user_roles表结构正常")
            
            RolePermission.query.first()
            print("✅ role_permissions表结构正常")
            
        except Exception as e:
            print(f"❌ 数据库表结构问题: {e}")
        
        # 6. 生成修复建议
        print("\n💡 6. 修复建议")
        print("-" * 40)
        
        if missing_permissions:
            print("需要添加缺失的权限:")
            for perm in missing_permissions:
                print(f"  - {perm}")
        
        if total_permissions < 90:
            print(f"当前权限数({total_permissions})少于预期(90个)")
            print("建议检查权限初始化脚本")
        
        if admin_user and len(all_admin_permissions) < 90:
            print(f"系统管理员权限数({len(all_admin_permissions)})少于预期(90个)")
            print("建议运行权限补全脚本")
        
        print("\n" + "="*80)
        return {
            'total_permissions': total_permissions,
            'admin_permissions': len(all_admin_permissions) if admin_user else 0,
            'missing_permissions': missing_permissions,
            'admin_exists': admin_user is not None,
            'admin_role_exists': admin_role is not None
        }

if __name__ == '__main__':
    result = comprehensive_permission_diagnosis()
    print(f"\n📋 诊断完成 - 权限数: {result['total_permissions']}, 管理员权限: {result['admin_permissions']}")
